import { Entity, IEntity } from "../entity/Entity";
import { Tile } from "../tile/Tile";
import { Player } from "../entity/Player";
import { CocosUtils } from "../utils/CocosUtils";
import { JsonAsset } from "cc";
import { ILevel } from "../Interfaces";

export type IRecord = Array<IEntity>;

export class DataManager {

    private static _instance: DataManager;

    public static get instance(): DataManager {
        return this._instance || (this._instance = new DataManager());
    }

    private constructor() { }

    public isAssetsLoaded: boolean = false;

    private _levelIndex: number = 0;
    private _levelData: ILevel = null;

    public tileInfo: Array<Array<Tile>> = [];
    public doors: Array<Entity> = [];
    public bursts: Array<Entity> = [];
    public enemies: Array<Entity> = [];
    public spikes: Array<Entity> = [];

    public player: Player = null;

    public records: IRecord[] = [];

    public entities: Array<Entity> = [];

    public get currentLevel(): ILevel {
        return this._levelData;
    }

    public addEntity(entity: Entity): void {
        this.entities.push(entity);
        if (entity.type === Entity.Type.SKELETON_WOODEN || entity.type === Entity.Type.SKELETON_IRON) {
            this.enemies.push(entity);
        } else if (entity.type === Entity.Type.DOOR) {
            this.doors.push(entity);
        } else if (entity.type === Entity.Type.BURST) {
            this.bursts.push(entity);
        } else if (entity.type === Entity.Type.SPIKES) {
            this.spikes.push(entity);
        }
    }

    public init(): void {
        this._levelIndex = 1;
        this.reset();
    }

    public reset(ignoreLevel: boolean = true): void {
        this.tileInfo = [];
        this.doors = [];
        this.bursts = [];
        this.enemies = [];
        this.spikes = [];
        this.player = null;
        this.records = [];
        this.entities = [];

        if (!ignoreLevel) {
            this._levelIndex = 1;
        }
        this._levelData = CocosUtils.getAsset(`config/level${this._levelIndex}`, JsonAsset).json as ILevel;
    }

    public nextLevel(): void {
        this._levelIndex++;
    }
}